const Router = require("@koa/router");
const router = new Router();
const {
  PublishCompanion,
  SignUpPartner,
  CompanionQuery,
  CompanionDetails,
  ManagingMember,
  Resreturn,
} = require("@/config/valiData");
const {
  modelCompanios,
  modelSignUp,
  modelUser,
} = require("@/models/collection");
const { Auth } = require("@/token/auth");
const { looKupCompanion } = require("@/config/lookup");

const moment = require("moment");
const { default: mongoose } = require("mongoose");
moment.locale("zh-cn");
//更新moment时间格式
moment.updateLocale("zh-cn", {
  relativeTime: {
    future: "in %s内",
    past: "%s 前",
    s: "刚刚",
    ss: "%d 秒",
    m: "1 分钟",
    mm: "%d 分钟",
    h: "1 小时",
    hh: "%d 小时",
    d: "1 天",
    dd: "%d 天",
    w: "1 周",
    ww: "%d 周",
    M: "1 月",
    MM: "%d 月",
    y: "1 年",
    yy: "%d 年",
  },
});

//发布结伴
router.post("/initiating-partner", new Auth().m, async (ctx) => {
  const {
    description,
    image,
    city,
    full_address,
    companion_time,
    number_of_people,
  } = ctx.request.body;
  PublishCompanion(
    description,
    image,
    city,
    full_address,
    companion_time,
    number_of_people
  );
  await modelCompanios.create({
    uid: ctx.auth.uid,
    description,
    image,
    city,
    full_address,
    companion_time,
    companion_timestamp: moment(companion_time).unix(),
    number_of_people,
  });
  ctx.body = {
    code: 200,
    message: "发布成功",
  };
});

//报名结伴
router.post("/sign-up-partner", new Auth().m, async (ctx) => {
  const { singup_id, contact_inform, gender, introduce } = ctx.request.body;
  SignUpPartner(singup_id, contact_inform, gender, introduce);
  await modelSignUp.create({
    singup_id,
    user_uid: ctx.auth.uid,
    contact_inform,
    gender,
    introduce,
  });
  ctx.send("SUCCESS", 200, "报名成功");
});

// 获取结伴城市
router.get("/companion-city", async (ctx) => {
  try {
    const res = await modelCompanios.aggregate([
      {
        $group: {
          _id: "$city",
        },
      },
      {
        $project: {
          _id: 0,
          city: "$_id",
        },
      },
    ]);

    res.unshift({ city: "推荐" });
    ctx.send("SUCCESS", 200, res);
  } catch (error) {
    ctx.send("FAIL", 500, error.message);
  }
});

// 首页筛选活动
router.get("/companion-query", async (ctx) => {
  const { city, keyword, page = 1 } = ctx.query;
  CompanionQuery(city, keyword, page);

  // 构建查询条件
  const match = buildMatchCondition(city, keyword);

  // 获取分页数据
  const companions = await modelCompanios.aggregate([
    { $match: match },
    { $sort: { companion_timestamp: -1 } },
    { $skip: (page - 1) * 6 },
    { $limit: 6 },
    looKupCompanion().model_user,
    looKupCompanion().model_signup,
    {
      $project: {
        _id: 1,
        description: 1,
        image: 1,
        city: 1,
        full_address: 1,
        companion_time: 1,
        number_of_people: 1,
        timestamp: 1,
        "author_data.nickname": 1,
        "author_data.avatarUrl": 1,
        signups: { $size: "$signups" },
      },
    },
  ]);

  // 处理时间显示
  const result = companions.map((item) => ({
    ...item,
    timestamp: formatRelativeTime(item.timestamp),
  }));

  ctx.send("SUCCESS", 200, result);
});

// 辅助函数：构建查询条件
const buildMatchCondition = (city, keyword) => {
  const timeRanges = {
    本月出发: {
      $gte: moment().startOf("month").unix(),
      $lte: moment().endOf("month").unix(),
    },
    下月出发: {
      $gte: moment().add(1, "month").startOf("month").unix(),
      $lte: moment().add(1, "month").endOf("month").unix(),
    },
  };

  const match = {};

  if (city !== "推荐") {
    match.city = city;
  }

  if (city === "推荐") {
    match.companion_timestamp = {
      $gte: moment().unix(),
    };
  }

  if (keyword !== "全部" && timeRanges[keyword]) {
    match.companion_timestamp = timeRanges[keyword];
  }

  return match;
};

// 辅助函数：格式化相对时间
const formatRelativeTime = (timestamp) => {
  const diff = moment().diff(timestamp * 1000, "seconds");
  return diff < 60 ? `${diff}秒前` : moment(timestamp * 1000).fromNow();
};

// 获取结伴详情
router.get("/companion-details", async (ctx) => {
  try {
    const { id } = ctx.query;
    CompanionDetails(id);

    const res = await modelCompanios.aggregate([
      {
        $match: {
          _id: new mongoose.Types.ObjectId(id),
        },
      },
      {
        $lookup: {
          from: modelUser.collection.name,
          localField: "uid",
          foreignField: "uid",
          as: "author_data",
        },
      },
      {
        $lookup: {
          from: modelSignUp.collection.name,
          localField: "_id",
          foreignField: "singup_id",
          as: "signups",
        },
      },
      {
        $lookup: {
          from: modelUser.collection.name,
          localField: "signups.user_uid",
          foreignField: "uid",
          as: "signup_users",
        },
      },
      {
        $project: {
          _id: 1,
          description: 1,
          image: 1,
          city: 1,
          full_address: 1,
          companion_time: 1,
          number_of_people: 1,
          timestamp: 1,
          author_data: { $arrayElemAt: ["$author_data", 0] },
          signups: {
            $map: {
              input: "$signups",
              as: "signup",
              in: {
                gender: "$$signup.gender",
                avatarUrl: {
                  $let: {
                    vars: {
                      user: {
                        $arrayElemAt: [
                          {
                            $filter: {
                              input: "$signup_users",
                              as: "user",
                              cond: {
                                $eq: ["$$user.uid", "$$signup.user_uid"],
                              },
                            },
                          },
                          0,
                        ],
                      },
                    },
                    in: "$$user.avatarUrl",
                  },
                },
                nickname: {
                  $let: {
                    vars: {
                      user: {
                        $arrayElemAt: [
                          {
                            $filter: {
                              input: "$signup_users",
                              as: "user",
                              cond: {
                                $eq: ["$$user.uid", "$$signup.user_uid"],
                              },
                            },
                          },
                          0,
                        ],
                      },
                    },
                    in: "$$user.nickname",
                  },
                },
              },
            },
          },
        },
      },
    ]);

    // 处理相对时间
    res.forEach((item) => {
      const diff = moment().diff(item.timestamp * 1000, "seconds");
      item.timestamp =
        diff < 60 ? `${diff}秒前` : moment(item.timestamp * 1000).fromNow();
    });

    ctx.send("SUCCESS", 200, res);
  } catch (error) {
    ctx.send("FAIL", 500, error.message);
  }
});

//查询是否已经报名
router.get("/signup-query", new Auth().m, async (ctx) => {
  const { id } = ctx.query;
  CompanionDetails(id);
  const res_a = await modelCompanios.find({
    _id: id,
    uid: ctx.auth.uid,
  });
  const res_b = await modelSignUp.find({
    singup_id: id,
    user_uid: ctx.auth.uid,
  });
  let queryRes = "";
  if (res_a.length > 0) {
    //用户自己发布的
    queryRes = "001";
  } else {
    if (res_b.length > 0) {
      //用户已经报名
      queryRes = "002";
    } else {
      //用户未报名
      queryRes = "003";
    }
  }
  ctx.send("SUCCESS", 200, queryRes);
});

//我参与的活动
router.get("/par-in-activities", new Auth().m, async (ctx) => {
  try {
    const { page } = ctx.query;
    const res = await modelSignUp.aggregate([
      {
        $match: {
          user_uid: ctx.auth.uid,
        },
      },
      {
        $sort: {
          timestamp: -1,
        },
      },
      {
        $skip: (page - 1) * 6,
      },
      {
        $limit: 6,
      },
      {
        $lookup: {
          from: modelCompanios.collection.name,
          localField: "singup_id",
          foreignField: "_id",
          as: "my_companion",
        },
      },
      {
        $unwind: "$my_companion",
      },
      {
        $lookup: {
          from: modelSignUp.collection.name,
          localField: "singup_id",
          foreignField: "singup_id",
          as: "signpCount",
        },
      },
      {
        $lookup: {
          from: modelUser.collection.name,
          localField: "my_companion.uid",
          foreignField: "uid",
          as: "author_data",
        },
      },
      {
        $project: {
          _id: "$my_companion._id",
          description: "$my_companion.description",
          image: "$my_companion.image",
          city: "$my_companion.city",
          full_address: "$my_companion.full_address",
          companion_time: "$my_companion.companion_time",
          number_of_people: "$my_companion.number_of_people",
          timestamp: "$my_companion.timestamp",
          author_data: {
            nickname: { $arrayElemAt: ["$author_data.nickname", 0] },
            avatarUrl: { $arrayElemAt: ["$author_data.avatarUrl", 0] },
          },
          count: { $size: "$signpCount" },
        },
      },
    ]);

    const result = res.map((item) => ({
      ...item,
      timestamp: formatRelativeTime(item.timestamp),
    }));

    ctx.send("SUCCESS", 200, result);
  } catch (error) {
    ctx.send("FAIL", 500, error.message);
  }
});

// 我发起的活动
router.get("/my-in-activities", new Auth().m, async (ctx) => {
  try {
    const { page } = ctx.query;
    Resreturn(page);

    const res = await modelCompanios.aggregate([
      {
        $match: {
          uid: ctx.auth.uid,
        },
      },
      {
        $sort: {
          timestamp: -1,
        },
      },
      {
        $skip: (page - 1) * 6,
      },
      {
        $limit: 6,
      },
      {
        $lookup: {
          from: modelUser.collection.name,
          localField: "uid",
          foreignField: "uid",
          as: "author_data",
        },
      },
      {
        $lookup: {
          from: modelSignUp.collection.name,
          localField: "_id",
          foreignField: "singup_id",
          as: "signups",
        },
      },
      {
        $project: {
          _id: 1,
          description: 1,
          image: 1,
          city: 1,
          full_address: 1,
          companion_time: 1,
          number_of_people: 1,
          timestamp: 1,
          author_data: {
            nickname: { $arrayElemAt: ["$author_data.nickname", 0] },
            avatarUrl: { $arrayElemAt: ["$author_data.avatarUrl", 0] },
          },
          count: { $size: "$signups" },
        },
      },
    ]);

    const result = res.map((item) => ({
      ...item,
      timestamp: formatRelativeTime(item.timestamp),
    }));

    ctx.send("SUCCESS", 200, result);
  } catch (error) {
    ctx.send("FAIL", 500, error.message);
  }
});

//管理成员
router.get("/managing-member", new Auth().m, async (ctx) => {
  try {
    const { id, page } = ctx.query;
    ManagingMember(id, page);

    const res = await modelSignUp.aggregate([
      {
        $match: {
          singup_id: new mongoose.Types.ObjectId(id),
        },
      },
      {
        $sort: {
          timestamp: -1,
        },
      },
      {
        $skip: (page - 1) * 6,
      },
      {
        $limit: 6,
      },
      {
        $lookup: {
          from: modelUser.collection.name,
          localField: "user_uid",
          foreignField: "uid",
          as: "author_data",
        },
      },
      {
        $project: {
          _id: 1,
          contact_inform: 1,
          gender: 1,
          introduce: 1,
          timestamp: 1,
          author_data: {
            nickname: { $arrayElemAt: ["$author_data.nickname", 0] },
            avatarUrl: { $arrayElemAt: ["$author_data.avatarUrl", 0] },
          },
        },
      },
    ]);

    const result = res.map((item) => ({
      ...item,
      timestamp: formatRelativeTime(item.timestamp),
    }));

    ctx.send("SUCCESS", 200, result);
  } catch (error) {
    ctx.send("FAIL", 500, error.message);
  }
});
module.exports = router.routes();
